package com.jf.identity.aop;

import com.jf.identity.datasource.TargetDataSource;
import com.jf.identity.entity.ExamBaseParam;
import com.jf.identity.holder.DataSourceKeyHolder;
import com.jf.identity.holder.ExamBaseParamHolder;
import com.jf.identity.util.Params;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author FCG
 */
@Component
@Aspect
@Order(0)
public class DataSourceAop {
    @Resource
    private DataSourceKeyHolder dataSourceKeyHolder;
    @Resource
    private ExamBaseParamHolder examBaseParamHolder;

    @Pointcut("execution(* com.jf.identity.dao.visexamid.*.*(..))")
    private void visExamIdPoint() {

    }

    @Pointcut("execution(* com.jf.identity.dao.dc.*.*(..))")
    private void dcPoint() {

    }

    @Pointcut("execution(* com.jf.identity.dao.vis.*.*(..))")
    private void visPoint() {

    }

    @Around("visExamIdPoint()")
    public Object changeDbByExamId(ProceedingJoinPoint joinPoint) throws Throwable {
        ExamBaseParam examParam = examBaseParamHolder.getExamBaseParam();
        examParam = Params.isBlank(examParam, "考试信息");
        String examId = Params.isBlank(examParam.getExamId(), "examId");
        dataSourceKeyHolder.setDataSourceKey(TargetDataSource.JF_VIS_DB + examId);
        Object result;
        try {
            result = joinPoint.proceed();
        } finally {
            //清空threadLocal,防止内存泄露
            dataSourceKeyHolder.remove();
        }
        return result;
    }

    @Around("dcPoint()")
    public Object changeDbToJfdcdb(ProceedingJoinPoint joinPoint) throws Throwable {
        dataSourceKeyHolder.setDataSourceKey(TargetDataSource.JF_DC_DB);
        Object result;
        try {
            result = joinPoint.proceed();
        } finally {
            dataSourceKeyHolder.remove();
        }
        return result;
    }

    @Around("visPoint()")
    public Object changeDbtoJfVisDb(ProceedingJoinPoint joinPoint) throws Throwable {
        dataSourceKeyHolder.setDataSourceKey(TargetDataSource.JF_VIS_DB);
        Object result;
        try {
            result = joinPoint.proceed();
        } finally {
            dataSourceKeyHolder.remove();
        }
        return result;
    }
}
